package com.chii.gateway.service.impl;

import com.chii.gateway.client.AuthClient;
import com.chii.gateway.service.IAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.stream.Stream;
@Service
public class AuthService implements IAuthService {

    @Autowired
    private AuthClient authClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 不需要网关签权的url配置(/oauth,/open)
     * 默认/oauth开头是不需要的
     */
    @Value("${gate.ignore.authentication.startWith}")
    private String ignoreUrls = "/oauth";


    @Override
    public boolean ignoreAuthentication(String url) {
        return Stream.of(this.ignoreUrls.split(",")).anyMatch(ignoreUrl -> url.startsWith(StringUtils.trim(ignoreUrl)));

    }

    @Override
    public boolean invalidToken(String token) {
        // 是否无效true表示无效
//        boolean invalid = Boolean.TRUE;
//        String responeInfo =  authClient.checkToken(token);


        // 检查 access_token 的有效性
        String formatKey = String.format("access:%s", token);
        Boolean hasKey = stringRedisTemplate.hasKey(formatKey);
        return hasKey;
    }
}
